﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Timers;
using System.Windows.Input;
using System.Windows;

namespace SharpSoft.WPF.Video
{
    public partial class PlayerProgressbar : Slider
    {
        Timer t = new Timer(900);
        public PlayerProgressbar()
        {
            this.InitializeComponent();
            t.Elapsed += T_Elapsed;
        }

        private void T_Elapsed(object sender, ElapsedEventArgs e)
        {
            changeValue();
        }

        void changeValue()
        {
            if (!Dispatcher.CheckAccess())
            {
                this.Dispatcher.Invoke(new Action(changeValue));
                return;
            }
            if (RelevanceMeidaElement != null)
            {
                this.Value = RelevanceMeidaElement.Position.TotalSeconds;
            }
        }

        protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseLeftButtonUp(e);
            if (RelevanceMeidaElement != null)
            {
                RelevanceMeidaElement.Position = TimeSpan.FromSeconds(this.Value);
            }

        }

        private MediaElement _RelevanceMeidaElement;
        /// <summary>
        /// 获取或设置关联的媒体控件
        /// </summary>
        public MediaElement RelevanceMeidaElement
        {
            get { return _RelevanceMeidaElement; }
            set
            {
                _RelevanceMeidaElement = value;
                if (_RelevanceMeidaElement!=null)
                {
                    _RelevanceMeidaElement.MediaOpened += _RelevanceMeidaElement_MediaOpened;
                }
            }
        }

        private void _RelevanceMeidaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            Action a = delegate { this.Maximum = RelevanceMeidaElement.NaturalDuration.TimeSpan.TotalSeconds;};
            if (!this.Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(a);
            }
            else
            {
                a();
            }
            
        }
    }
}
